<template>
  <base-breadcrumb :breadcrumb="!isAudit">
    <template>
      <a-spin :spinning="loading">
        <a-tabs type="card" @change.self="onChangeStep">
          <a-tab-pane key="1" tab="分包签证指令单">
            <instructionSheet :isAudit="true" ref="instructionSheet" :instructionSheetData="form.visaSerVO" :editModel="0"></instructionSheet>
          </a-tab-pane>
          <a-tab-pane key="2" tab="分包签证事实确认单">
            <confirmationFact :isAudit="true" :confirmationFactData="form.factBusinessDTO" :editModel="0"></confirmationFact>
          </a-tab-pane>
          <a-tab-pane key="3" tab="分包签证经济签证单">
            <visaSingle :isAudit="true" :visaSingleData="form.economicVisaBusinessDTO" :editModel="0"></visaSingle>
          </a-tab-pane>
        </a-tabs>
        <a-form-model ref="ruleForm" :model="form.economicVisaBusinessDTO" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="rules">
          <a-card :bordered="false">
            <title-name title="审批"></title-name>
            <custom-form :isEmit="false" :form="form.economicVisaBusinessDTO" :formList="auditFormList" :editModel="''"> </custom-form>
            <Consultation
            :proc-inst-id="procInstId"
            :is-show-btn="$route.query.isMonitoring ? ($route.query.monitoringType==='process' ? true: false): true"
            :task-name="taskName"
            :sub-approver-list.sync="subApproverList"
          >
            <template slot="approverButton">
              <a-button type="primary" :loading="loading.REJECT" @click="handleSave('REJECT')">审批不通过</a-button>
              <a-button type="primary" :loading="loading.PASS" class="ml12" @click="handleSave('PASS')">审批通过</a-button>
            </template>
          </Consultation>
          </a-card>
          <a-card>
            <template>
              <title-name title="审批流程信息" />
              <div class="btns-wrapp mb20">
                <a-button type="primary" @click="visibleState.auditProcess = true"> 审批流程图 </a-button>
              </div>
              <a-spin tip="流程信息加载中..." :spinning="flowRequesting" />
              <a-table :columns="columnApprove" :data-source="approveInfos" bordered>
                <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
                <template slot="opinions" slot-scope="text">
                  <a-tooltip placement="topLeft">
                    <template slot="title">
                      <span> {{ text }}</span>
                    </template>
                    <span> {{ text }}</span>
                  </a-tooltip>
                </template>
              </a-table>
            </template>
          </a-card>
          <!-- 页脚操作栏 -->
          <div v-if="!isConsultation" class="btn_box page-btn-right-top">
            <!-- <a-button v-if="typess == 'read'" type="primary" @click="handleClose">关闭</a-button> -->
            <a-button @click="handleActiveClose">关闭</a-button>
          </div>
          <ApprovalDetails :title="'审批流程信息'" :business-id="id" :visible="visibleState.auditProcess" @cancel="visibleState.auditProcess = false" @confirm="visibleState.auditProcess = false" />
        </a-form-model>
      </a-spin>
    </template>
  </base-breadcrumb>
</template>
<script>
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分公司
import instructionSheet from './components/instructionSheet'
import confirmationFact from './components/confirmationFact'
import dataSummary from './components/dataSummary'
import visaSingle from './components/visaSingle'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import { getDetail, updateVisaSingle } from '@/api/businessAffairs/subcontractVisa'
import moment from 'moment'
import Vue from 'vue'
import ApprovalDetails from '@/components/approvalDetails'
import Consultation from '@/views/matters/approval/components/consultation'
import { getOrgEmployeesListBy } from '@/api/commons'
import { getProcessNodeList, completeTask } from '@/api/process'
import { columnApprove } from './model.js'
export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    SelectSubCompany,
    SelectProject,
    SelectSubcontractor,
    instructionSheet,
    confirmationFact,
    dataSummary,
    visaSingle,
    ApprovalDetails,
    Consultation
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      columnApprove,
      visibleState: {
        auditProcess: false
      },
      form: {
        branchComId: '',
        projectId: '',
        name: '',
        visaSerVO: { serDTOS: [] },
        fileSerDTO: { fineDTOS: [] },
        factBusinessDTO: { businessAgentId: '', projectDeptId: '' },
        economicVisaBusinessDTO: {},
        contractNameId: ''
      },
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      loading: false,
      current: -1,
      currentStep: -1,
      rules: {
        initialVisaEnd: [{ required: true, message: '请输入' }],
        initialVisaTaxEnd: [{ required: true, message: '请输入' }]
      },
      //审批相关
      approveInfos: [], // 审批流程信息
      procInstId: '', //当前流程实例ID
      taskId: '', //当前流程节点ID
      processName: '', //流程名称
      taskName: '', //当前流程节点名称
      taskDefKey: '', //任务标识
      currentTime: '', //当前审批时间
      currentUser: '', //当前审批人
      flowRequesting: false,
      detailUrl: null, //详情地址

      assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
      assignCode: '', //候选组编码 岗位编码
      assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
      businessType: '', //业务类型 0 项目
      // 下级审批人
      subApproverList: []
    }
  },
  computed: {
    auditFormList() {
      return [
        {
          keyName: 'initialVisaEnd',
          type: 'BaseInputNumber',
          label: '审定签证金额(不含税)(元)',

          precision: 2,
          change: (e) => {
            this.form.economicVisaBusinessDTO.initialVisaTotalEnd = (this.form.economicVisaBusinessDTO.initialVisaEnd || 0) + (this.form.economicVisaBusinessDTO.initialVisaTaxEnd || 0)
          }
        },
        {
          keyName: 'initialVisaTaxEnd',
          type: 'BaseInputNumber',
          label: '审定签证税金(元)',

          precision: 2,
          change: (e) => {
            this.form.economicVisaBusinessDTO.initialVisaTotalEnd = (this.form.economicVisaBusinessDTO.initialVisaEnd || 0) + (this.form.economicVisaBusinessDTO.initialVisaTaxEnd || 0)
          }
        },
        {
          keyName: 'initialVisaTotalEnd',
          type: 'BaseInputNumber',
          disabled: true,
          label: '审定签证金额(含税(元)'
        },
        {
          keyName: 'opinions',
          type: 'BaseTextarea',
          label: '审批意见',
          span: 24
        },

        {
          keyName: 'taskName',
          type: 'BaseInput',
          label: '当前节点名称',
          disabled: true,

          span: 8
        },
        {
          keyName: 'currentUser',
          type: 'BaseInput',
          label: '审批人',
          disabled: true,

          span: 8
        },
        {
          keyName: 'currentTime',
          type: 'BaseInput',
          label: '审批时间',
          disabled: true,

          span: 8
        },
        {
          keyName: 'durationInMillis',
          type: 'BaseInput',
          label: '当前滞留时间',
          disabled: true,
          span: 8
        }
      ]
    }
  },
  mounted() {
    this.getDetailReq() //格式化审批流数据
  },
  methods: {
    initStyle() {
      try {
        setTimeout(() => {
          const requireDom = document.querySelectorAll('.ant-form-item-required')
          requireDom.forEach((item) => {
            item.parentNode.nextSibling.children[0].children[0].classList.add('requiredFormItem') // 找到'.ant-form-item-children'元素添加样式
          })
        }, 0)
      } catch {}
    },
    formattingData() {
      this.form.user = JSON.parse(sessionStorage.getItem('ycloud-user_info')).username
      this.id = this.$route.query.id
      const { type, code, level, btype, businessId, procInstId, name, processName, detailUrl, taskId, taskDefKey, durationInMillis } = this.$route.query
      if (type) {
        this.assignType = type
        this.assignCode = code
        this.assignLevel = level
        this.businessType = btype
      }
      this.id = businessId
      this.detailId = this.$route.query.detailId
      this.typess = this.$route.query.typess
      // this.taskDefKey = 'GS_CWZJBJL_AUDIT'
      if (!this.id) {
        this.$error({ content: '无指定业务ID，将自动关闭' })
        setTimeout(() => {
          window.close()
        }, 1500)
        return
      }
      console.log(this.$route.query)
      this.procInstId = procInstId
      this.form.economicVisaBusinessDTO.currentUser = Vue.getAcloudProvider().getUserInfo().name
      this.form.economicVisaBusinessDTO.taskName = decodeURIComponent(name)
      this.form.economicVisaBusinessDTO.durationInMillis = durationInMillis
      this.processName = decodeURIComponent(processName)
      document.title = this.processName + '-' + this.taskName
      if (detailUrl) {
        this.detailUrl = decodeURIComponent(detailUrl)
      }
      this.taskId = taskId
      this.taskDefKey = taskDefKey

      this.form.economicVisaBusinessDTO.currentTime = moment().format('YYYY-MM-DD HH:mm')
      this.$route.meta.title = '分包签证经济签证单审批'

      this.getProcessNodes()
    },
    //流程节点信息
    getProcessNodes() {
      this.flowRequesting = true
      getProcessNodeList({ procInstId: this.procInstId, pageNo: 1, pageSize: 100 })
        .then((res) => {
          if (res.code === 200) {
            const data = res.data
            const userIds = data.map((d) => {
              if (d.formData) {
                d.formData = JSON.parse(d.formData)
              }
              return d.assignee
            })
            getOrgEmployeesListBy({ userIds, delete: true }).then((employees) => {
              this.flowRequesting = false
              res.data.forEach((r) => {
                employees.data.some((e) => {
                  if (e.userId === r.assignee) {
                    r.userName = e.name
                    return true
                  }
                })
              })

              this.approveInfos = res.data
            })
          }
        })
        .catch(() => {
          this.flowRequesting = false
        })
    },
    onChangeStep(current) {
      console.log(current)
      this.current = current
    },
    getDetailReq() {
      this.loading = true
      getDetail({ id: this.id }).then((res) => {
        //数据转换
        res.data.visaSerVO.isOtherDeduction = res.data.visaSerVO.isOtherDeduction ? 1 : 0
        //后续步骤要显示步骤一的字段后端没反
        if (res.data.factBusinessDTO) {
          res.data.factBusinessDTO.branchComId = res.data.visaSerVO.branchComId
          res.data.factBusinessDTO.projectId = res.data.visaSerVO.projectId
          res.data.factBusinessDTO.subContractUnitId = res.data.visaSerVO.subContractUnitId
          res.data.factBusinessDTO.name2 = res.data.visaSerVO.name
          res.data.factBusinessDTO.constructionSite = res.data.visaSerVO.constructionSite
          res.data.factBusinessDTO.codeStep1 = res.data.visaSerVO.code
        }
        if (res.data.economicVisaBusinessDTO) {
          res.data.economicVisaBusinessDTO.branchComId = res.data.visaSerVO.branchComId
          res.data.economicVisaBusinessDTO.projectId = res.data.visaSerVO.projectId
          res.data.economicVisaBusinessDTO.subContractUnitId = res.data.visaSerVO.subContractUnitId
          res.data.economicVisaBusinessDTO.name3 = res.data.visaSerVO.name
          res.data.economicVisaBusinessDTO.constructionSite = res.data.visaSerVO.constructionSite
          res.data.economicVisaBusinessDTO.matters = res.data.visaSerVO.matters
        }
        if (res.data.fileSerDTO) {
          res.data.fileSerDTO.isOtherDeduction = res.data.visaSerVO.isOtherDeduction
          res.data.fileSerDTO.initialVisa = res.data.economicVisaBusinessDTO.initialVisa
          res.data.fileSerDTO.initialVisaTax = res.data.economicVisaBusinessDTO.initialVisaTax
          res.data.fileSerDTO.initialVisaTotal = res.data.economicVisaBusinessDTO.initialVisaTotal
        }
        if (res.data.visaSerVO) {
          this.current = 0
          this.currentStep = 0
        }
        if (res.data.factBusinessDTO) {
          this.current = 1
          this.currentStep = 1
        }
        if (res.data.economicVisaBusinessDTO) {
          this.current = 2
          this.currentStep = 2
        }
        if (res.data.fileSerDTO) {
          this.current = 3
          this.currentStep = 3
        }
        this.loading = false
        //设置默认审批意见
        res.data.economicVisaBusinessDTO.opinions = '同意'
        this.form = res.data
        this.formattingData()
        this.initStyle()
        console.log(this.form)
      })
    },
    /**
     * 提交表单
     */
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })

      return flag
    },
    // 处理增、删、改操作
    handleSave(status) {
      if (this.loadingBtn[status]) return

      if (status == 'PASS') {
        console.log(this.validateForm)
        if (this.validateForm()) {
          this.handelApproval(status)
        }
      } else {
        this.handelUnApproval(status)
      }
    },
    handelApproval(staus) {
      // 审批通过
      const _this = this
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(false, _this.createApproverList(_this.subApproverList))
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel() {}
      })
    },
    notifyParent() {
      window.opener.postMessage('finish', window.location.origin)
    },
    handelUnApproval(staus) {
      // 审批不通过
      const _this = this
      const confirmWin = this.$confirm({
        title: '警告提醒！',
        content: '确定审批不通过？',
        okType: 'danger',
        onOk() {
          return new Promise((resolve, reject) => {
            _this
              .submit(true, staus)
              .then(() => {
                resolve()
                confirmWin.destroy()
              })
              .catch(() => reject)
          }).catch(() => this.$error({ content: '审批提交失败，请稍后重试' }))
        },
        onCancel() {}
      })
    },
    /**
     * @description: 组装下级审批人数据
     * @param {array} subApproverList 下级审批人表格数据
     * @return {object} 下级审批人数据
     */
    createApproverList(subApproverList) {
      const subordinateApproverList = {}
      subApproverList.forEach((item) => {
        if (item?.approver && item.approver.length > 0) {
          subordinateApproverList[item.taskInfo.id] = {
            assgins: item.approver?.map((el) => el.key).join(','),
            assignTypeEnum: 2
          }
        }
      })
      return subordinateApproverList
    },
    async submit(reject) {
      if (reject && this.form.economicVisaBusinessDTO.opinions == '同意') {
        this.form.economicVisaBusinessDTO.opinions = '不同意'
      } else if (!reject && this.form.economicVisaBusinessDTO.opinions == '不同意') {
        this.form.economicVisaBusinessDTO.opinions = '同意'
      }
      //判断是否是最后节点
      if (!reject) {
        this.form.economicVisaBusinessDTO.auditStatus = 'DRAFT'
        await updateVisaSingle(this.form.economicVisaBusinessDTO)
      }

      const data = {
        formData: {
          opinions: this.form.economicVisaBusinessDTO.opinions,
          reject
        },
        procInstId: this.procInstId,
        taskId: this.taskId,
        userId: Vue.getAcloudProvider().getUserInfo().id
      }
      console.log(data)

      if (reject) {
        data['variables'] = { reject: true }
      }
      return completeTask(data)
        .then((res) => {
          if (res.status === 200) {
            this.notifyParent() // 通知父窗口
            // this.$success({
            //   content: '审批提交成功，即将自动关闭当前窗口',
            //   onOk() {
                window.close()
            //   }
            // })
            // setTimeout(() => {
            //   window.close()
            // }, 2000)
          } else {
            this.$error({ content: '审批提交失败，请稍后重试' })
          }
          return res
        })
        .catch((err) => {
          return err
        })
    }
  }
}
</script>
